import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { ColumnsType } from 'antd/es/table';
import { Card, Table, Space, Button, Input, Tabs, DatePicker, Drawer, Typography, Modal, Tag } from 'antd';
import { SyncOutlined, PlusOutlined, CheckOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import request from '@/utils/request';
import moment from 'moment';

const { TabPane } = Tabs;
const { Text } = Typography;
const { RangePicker } = DatePicker;
const { Search } = Input;
const { confirm } = Modal;
const apiURL = '/api/services/app/PartTran/';
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
            visible: false,
            selectedRowKeys: [],
            pageIndex: 1,
            pageSize: 10,
            totalCount: 0,
            payload: {},
            record: {},
            keywords: undefined,
            startTime: undefined,
            endTime: undefined
        }
    }
    componentDidMount() {
        this.fetchDatas();
    }
    fetchDatas = () => {
        this.setState({ loading: true });
        const { pageIndex, pageSize, keywords } = this.state;
        var startTime = this.state.startTime
        var endTime = this.state.endTime
        if (!startTime) {
            var y = new Date().getFullYear();
            var m = new Date().getMonth();
            startTime = new Date(y, m, 1);
            endTime = new Date(y, m + 1, 0);
            startTime = new Date(startTime.setDate(startTime.getDate() + 1));
            endTime = new Date(endTime.setDate(endTime.getDate() + 1));
            this.setState({ startTime, endTime })
        }
        request(apiURL + 'FinCost', {
            method: 'POST',
            data: {
                SkipCount: (pageIndex - 1) * pageSize,
                MaxResultCount: pageSize,
                keywords,
                startTime,
                endTime,
                partCostMethod: 'AVG',
                desc: true
            },
        }).then((response) => {
            if (response && response.result) {
                var result = response.result;
                var dataSource = result.items;
                this.setState({ loading: false, dataSource, totalCount: result.totalCount, sumCost: result.sumCost, sumQty: result.sumQty });
            }
        });
    }
    onSelectChange = (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
    };
    onSearch = (keywords: any) => {
        this.setState({ keywords }, () => {
            this.fetchDatas();
        });
    }
    swithDrawer = (visible: boolean, record = null) => {
        this.setState({ visible, record });
    }
    tabChange = (key: any) => {
        var y = new Date().getFullYear();
        var m = key - 1;
        var startTime = new Date(y, m, 1);
        var endTime = new Date(y, m + 1, 0);
        startTime = new Date(startTime.setDate(startTime.getDate() + 1));
        endTime = new Date(endTime.setDate(endTime.getDate() + 1));
        let _this = this;
        this.setState({ startTime, endTime }, function () {
            _this.fetchDatas();
        });
    }
    checkOut = () => {
        let _this = this;
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '确定要结账？',
            onOk() {
                const { startTime, endTime } = _this.state;
                _this.setState({ loading2: true })
                request(apiURL + 'CheckOutTrans', {
                    method: 'POST',
                    params: {
                        startTime,
                        endTime,
                    },
                }).then((response) => {
                    if (response && response.success) {
                        _this.fetchDatas();
                    }
                    _this.setState({ loading2: false })
                });
            },
        });

    }
    onMonthChange = (value: any) => {
        if (value && value.length == 2) {
            var startTime = value[0].format('YYYY-MM-DD');
            var endTime = value[1].format('YYYY-MM-DD');
            let _this = this;
            this.setState({ startTime, endTime }, function () {
                _this.fetchDatas();
            });
        }
    }
    render() {
        const { loading, loading2, dataSource, selectedRowKeys, totalCount, pageSize, sumQty, sumCost } = this.state;
        const columns: ColumnsType<any> = [
            {
                title: '交易日期',
                dataIndex: 'tranDate',
                render: (text: Date) => moment(text).format('YYYY-MM-DD'),
                fixed: 'left',
                width: 110
            },
            {
                title: '状态',
                dataIndex: 'checkOut',
                render: (text: boolean) => <Tag color={text ? "green" : "red"}>{text ? "已结" : "未结"}</Tag>,
                fixed: 'left',
                width: 60
            },
            {
                title: '物料编码',
                dataIndex: 'partNum',
                fixed: 'left',
                width: 110
            },
            {
                title: '描述',
                dataIndex: 'partDescription',
                ellipsis: true,
            },
            {
                title: '交易数量',
                dataIndex: 'tranQty',
                align: 'right',
                width: 100
            },
            {
                title: '单位',
                dataIndex: 'um',
                width: 60
            },
            {
                title: '交易类型',
                dataIndex: 'tranType',
                width: 110
            },
            {
                title: '物料单位成本',
                dataIndex: 'mtlUnitCost',
                align: 'right',
                width: 80
            },

            {
                title: '仓库',
                dataIndex: 'wareHouseCode',
                width: 70
            },
            {
                title: '库位',
                dataIndex: 'binNum',
                width: 70
            },
            {
                title: '批次',
                dataIndex: 'lotNum',
                width: 70
            },
            {
                title: '工单',
                dataIndex: 'jobNum',
                width: 70
            },
            {
                title: '总成本',
                dataIndex: 'extCost',
                fixed: 'right',
                align: 'right',
                width: 100,
                render: (text: number) => (<Text strong>{text}</Text>),
            },
        ];
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        var months = []
        for (var m = 1; m <= 12; m++) {
            months.push(m)
        }
        const optionTab = months.map((m: any) => {
            return (
                <TabPane tab={m + '月'} key={m.toString()}></TabPane>
            );
        });
        var month = new Date().getMonth() + 1;
        return (
            <PageHeaderWrapper>
                <Card>
                    <Space>
                        <Button type="primary"
                            onClick={this.fetchDatas}
                            loading={loading}
                            icon={<SyncOutlined />} >刷新</Button>
                        <Button danger
                            onClick={this.checkOut}
                            loading={loading2}
                            icon={<CheckOutlined />} >账期结账</Button>
                        <Button hidden type="primary" icon={<PlusOutlined />} onClick={() => this.swithDrawer(true)}>新增</Button>
                        <Search style={{ width: 240 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch(value)} />
                        <RangePicker onChange={this.onMonthChange} />
                    </Space>
                </Card>
                <Card>
                    <Tabs
                        tabBarExtraContent={<Button type="link"><Tag color="magenta"><strong>交易量合计：{sumQty} 成本合计：￥{sumCost}</strong></Tag></Button>}
                        defaultActiveKey={month.toString()} onChange={this.tabChange} type="card">
                        {optionTab}
                    </Tabs>
                    <Table
                        rowKey="id"
                        loading={loading}
                        rowSelection={rowSelection}
                        columns={columns}
                        dataSource={dataSource}
                        scroll={{ x: 'max-content' }}
                        //scroll={{ x: '1800' }}
                        pagination={{
                            onChange: page => {
                                this.setState({ pageIndex: page }, () => {
                                    this.fetchDatas();
                                });
                            },
                            pageSize,
                            total: totalCount,
                        }}
                    />
                </Card>
                <Drawer
                    width={800}
                    placement="right"
                    closable={false}
                    onClose={() => this.swithDrawer(false)}
                    visible={this.state.visible}
                    destroyOnClose={true}
                >

                </Drawer>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp, user }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: user.currentUser,
}))(ViewPage);